<?php

class UserController extends GenesisController
{
    /**
     * Validates vars according to rules specified.
     *
     * @param string $username
     * @param string $firstname
     * @param string $lastname
     * @param int    $groupid
     * @param char   $gender
     * @param string $email
     * @param Date   $birthday
     * @return bool
     */
    private function validateParams($username, $firstname, $lastname, $groupid, $gender, $email, $birthday)
    {
        $errors = array();
        $validator = new Zend_Validate();
        $validator->addValidator(new Zend_Validate_Alnum())
                                  ->addValidator(new Zend_Validate_StringLength(2,10));

        if(!$validator->isValid($username)){
            $errors[] = "Please enter a valid user name";
        }

        if(!$validator->isValid($firstname)){
            $errors[] = "Please enter a valid first name";
        }

        if(!$validator->isValid($lastname)){
            $errors[] = "Please enter a valid last name";
        }

        $validator = new Zend_Validate();
        $validator->addValidator(new Zend_Validate_Digits())
                                  ->addValidator(new Zend_Validate_Between(1,4));

        if(!$validator->isValid($groupid)){
            $errors[] = "Please enter a valid group id";
        }

        if(!Zend_Validate::is($email, 'EmailAddress')){
            $errors[] = "Please enter a valid email address";
        }
        
         if(!Zend_Validate::is($birthday, 'Date', array("yy-mm-dd"))){
            $errors[] = "Please enter a valid birthday";
        }

        if ($gender != 'm' && $gender !='f'){
            $errors[] = "Please enter a valid gender";
        }

        return $errors;
    }

    /**
     * Adds user.
     *
     * Requires: _REQUEST['username'] , _REQUEST['firstname']
     *           _REQUEST['lastname'] , _REQUEST['groupid']
     *           _REQUEST['gender']   , _REQUEST['email']
     *           _REQUEST['password'] , _REQUEST['birthday']
     *
     */
    public function addUserAction() {
        $username      = $this->_request->getPost('username');
        $firstname    = $this->_request->getPost('firstname');
        $lastname       = $this->_request->getPost('lastname');
        $groupid         = $this->_request->getPost('groupid');
        $gender            = $this->_request->getPost('gender');
        $email               = $this->_request->getPost('email');
        $password       = $this->_request->getPost('password');
        $birthday       = $this->_request->getPost('birthday');

        $errors = $this->validateParams($username, $firstname, $lastname, $groupid, $gender, $email, $birthday);

        if(!Zend_Validate::is($password, 'StringLength', array('min' => 6, 'max' => 12))){
            $errors[] = "Please enter a valid password (between 6-12 characters)";
        }
        //die(var_export($errors,1));
        if (sizeof($errors) == 0) {
            $user = new Default_Model_Users();

            if ($user->isUsernameExists($username)) {
                $errors[] = "Username exists";
            } else {
                    $user->setUsername($username);
                    $user->setFirstName($firstname);
                    $user->setLastName($lastname);
                    $user->setUserMasterGroupId($groupid);
                    $user->setGender($gender);
                    $user->setEmail($email);
                    $user->setPassword(sha1($this->_config->sha1->salt.$password));
                    $user->setBirthday($birthday);
                    $user->save();
            }
       }
       $this->view->jsonMessage=json_encode($errors);
    }


    /**
     * Removes a user.
     *
     * Requires: _REQUEST['row_id']
     */
    public function removeUserRowAction() {
        $id=$this->getRequest()->getParam('row_id');
        if (!is_numeric($id))
            throw new Exception('row id is not numeric! contact admin');
        $user = new Default_Model_Users();
        $user->find($id);
        $user->deleteRowByPrimaryKey();
        $this->view->message=json_encode(array('success'=>1));
    }


    /**
     * Sets a users password.
     *
     * Requires: _REQUEST['row_id'], _REQUEST['password']
     */
    public function setUserPasswordAction() {

        $rowId=$this->getRequest()->getParam('row_id');
        $password=$this->getRequest()->getParam('password');



        $user = new Default_Model_Users();
        $user->find($rowId);
        $ret=array('success'=>1,'message'=>'done');
        if (!$user->getId())
            $ret=array('success'=>0,'message'=>'Cannot find user in DB');
        if(!Zend_Validate::is($password, 'StringLength', array('min' => 6, 'max' => 12))){
             $ret=array('success'=>0,'message'=>'Please enter a valid password (between 6-12 characters)');
        }
        $user->setPassword(sha1($this->_config->security->sha1->salt . $password));
        $user->save();
        $this->view->message=json_encode($ret);
    }

    /**
     * Handler for edit action of jqGrid usersTable.
     *
     * Requires: _REQUEST['username'] , _REQUEST['firstname']
     *           _REQUEST['lastname'] , _REQUEST['groupid']
     *           _REQUEST['gender']   , _REQUEST['email']
     *           _REQUEST['password'] , _REQUEST['birthday']
     *           _REQUEST['id']
     */
    public function setUsersListAction() {

        $id=$this->getRequest()->getParam('id');
        $firstname=$this->getRequest()->getParam('firstname');
        $lastname=$this->getRequest()->getParam('lastname');
        $username=$this->getRequest()->getParam('username');
        $birthday=$this->getRequest()->getParam('birthday');
        $gender=$this->getRequest()->getParam('gender');
        $email=$this->getRequest()->getParam('email');
        $groupid=$this->getRequest()->getParam('groupid');

        $errors = $this->validateParams($username, $firstname, $lastname, $groupid, $gender, $email, $birthday);
        if (sizeof($errors) == 0)
        {
                $user = new Default_Model_Users();
                $user->find($id);
                $user->setFirstName($firstname);
                $user->setLastName($lastname);
                $user->setUsername($username);
                $user->setBirthday($birthday);
                $user->setGender($gender);
                $user->setEmail($email);
                $user->setUserMasterGroupId($groupid);
                $user->save();
        }
    }

    /**
     * Gets users list from db according to page, rows, sidx and sord.
     *
     * Requires: _REQUEST['page'] , _REQUEST['rows']
     *           _REQUEST['sidx'] , _REQUEST['sord']
     *
     * Returns: Array where 'page'    => Page number
     *                      'total'   => Total number of pages
     *                      'records' => Total number of rows
     *                      'rows'    => Component usage rows as an Array
     *          Returned as json message in $view->jsonMessage
     */
    public function getUsersListAction() {

        $page = $this->getRequest()->getParam('page'); // get the requested page
        $limit = $this->getRequest()->getParam('rows'); // get how many rows we want to have into the grid
        $sidx = $this->getRequest()->getParam('sidx'); // get index row - i.e. user click to sort
        $sord = $this->getRequest()->getParam('sord'); // get the direction if(!$sidx) $sidx =1;


        $user 						= new Default_Model_Users();
        $records = $user->countAllRows();
        $list = $user->fetchListToArray(null, $sidx.' '.$sord, $limit, ($page-1)*$limit);
        $total=ceil(($records)/$limit);
        if ($page > $total)
                $page=$total;
        $rows=array();
        foreach ($list as $row) {
            $rows[]=array(
                'id'=>$row['id'],
                'cell'=>array($row['id'],
                              $row['first_name'],
                              $row['last_name'],
                              $row['username'],
                              $row['birthday'],
                              $row['gender'],
                              $row['email'],
                              $row['user_master_group_id'],
                              $row['timestamp'])
                );
        }
        $ret = array(
            'page'=>$page,
            'total'=>$total,
            'records'=>$records,
            'rows'=>$rows);
        $this->view->jsonMessage=json_encode($ret);

    }
    

    /**
     * List components action - loads required css and js for view.
     */
    public function listUsersAction()
    {           
        $this->view->headLink()->appendStylesheet('/js/jqGrid/themes/ui.jqgrid.css');
        $this->view->headScript()->appendFile('/js/jqGrid/js/i18n/grid.locale-en.js');
        $this->view->headScript()->appendFile('/js/jqGrid/js/jquery.jqGrid.js');
        
        $jqGridTheme=$this->_config->jqgrid->theme;
    }

    /**
     * Registers a user.
     */
    public function registerAction() {

        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity()) {
            $this->_helper->flashMessenger(array('success'=>0,'message'=>'cannot register while logged in.'));
            $this->_redirect('/index');
        }

        
        //TODO: should fix Zend_Loader so the class will be loaded automatically
        require_once('../application/forms/RegistrationForm.php');

        $this->view->registrationForm = new forms_RegistrationForm();
        
        
    }

   /**
    * Procceses a users registration.
    */
    public function registerProcessAction() {

        $auth = Zend_Auth::getInstance();

        $memberGroups = $this->_defaults['groups'];

        $memberGroups = array_flip($memberGroups);

        if ($auth->hasIdentity()) {
            $this->_helper->flashMessenger(array('success'=>0,'message'=>'cannot register while logged in.'));
            $this->_redirect('/index');
        }

        //TODO: should fix Zend_Loader so the class will be loaded automatically
        require_once('../application/forms/RegistrationForm.php');

        $this->view->registrationForm = new forms_RegistrationForm();

        $form = new forms_RegistrationForm();
        $formData = $this->_request->getPost();

        if (!$form->isValid($formData)) {
            foreach ($form->getErrorMessages() as $message)
                $this->_helper->flashMessenger(array('success'=>0,'message'=>$message));
            $this->_redirect('/index');
        }

        if ($formData['password'] != $formData['password2']) {
            $this->_helper->flashMessenger(array('success'=>0,'message'=>'passwords do not match.'));
            $this->_redirect('/index');
        }

        $users  = new Default_Model_Users();
        $users->setBirthday($formData['register_birthday']);
        $users->setEmail($formData['register_email']);
        $users->setFirstName($formData['register_firstname']);
        $users->setLastName($formData['register_lastname']);
        $users->setPassword(sha1($this->_config->security->sha1->salt.$formData['register_password']));
        $users->setUsername($formData['register_username']);
        $users->setGender($formData['register_gender']);
        $users->setUserMasterGroupId($memberGroups['member']);
        $users->save();
        
        $username=$formData['register_username'];
        $password=$formData['register_password'];

        $result=$this->_login($username,$password);

        if ($result->isValid()) 
            $this->_helper->flashMessenger(array('success'=>1,'message'=>"welcome $username."));
        else
            $this->_helper->flashMessenger(array('success'=>0,'message'=>"could not login after registration. please contact admin."));

        $this->_redirect('/');


    }

    

    private function _login($username,$password) {

        $dbAdapter = Zend_Db_Table::getDefaultAdapter();

        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password')
                ->setCredentialTreatment('SHA1(?)');

        $authAdapter->setIdentity($username)
                    ->setCredential($this->_config->security->sha1->salt . $password);

        $result = $authAdapter->authenticate($authAdapter);

        if ($result->isValid()) {
                   // get all info about this user from the login table
                     // ommit only the password, we don't need that
             $userInfo = $authAdapter->getResultRowObject(null, 'password');
                     // the default storage is a session with namespace Zend_Auth
             $auth = Zend_Auth::getInstance();
             $authStorage = $auth->getStorage();
             $authStorage->write($userInfo);
             $this->_helper->FlashMessenger(array('success'=>1,'message'=>"welcome $username."));
        } else
            foreach ($result->getMessages() as $message)
                $this->_helper->FlashMessenger(array('success'=>0,'message'=>$message));


        return $result;
        
    }

    public function loginAction() {

        if (!$this->_request->isPost()) {

            $this->_helper->flashMessenger(array('success'=>0,'message'=>'bad login attempt.'));
            $this->_redirect('/');

        }

        $form = new forms_LoginForm();
        $formData = $this->_request->getPost();

        if (!$form->isValid($formData)) {
            foreach ($form->getErrorMessages() as $message)
                $this->_helper->flashMessenger($message);
            $this->_redirect('/');
        }


        $username=$formData['username'];
        $password=$formData['password'];
        $auth=null;
        $result = $this->_login($username, $password);
        
        
        $this->_redirect('/');

    }

    public function logoutAction() {

        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('/');

    }

}







